<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { Page } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { notification, Popconfirm, Space, Button, Upload } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getInventories, deleteInventory, exportInventoryTemplate, exportInventories, importInventories } from '#/api/inventory';
import { columns, querySchema } from './inventory';
import { useVbenModal } from '@vben/common-ui';
import inventoryModal from './inventory-modal.vue';
import type { InventoryDto, InventoryManagementImportResult } from '#/api/inventory/types';
import { ref } from 'vue';
import {
  SvgDownloadIcon,
} from '@vben/icons';
import { useAccess } from '@vben/access';
const { hasAccessByCodes } = useAccess();
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      showCollapseButton: false,
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'creationTime',
      ['CreationTimeStart', 'CreationTimeEnd'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    showHeader:true
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getInventories({
          skipCount: (page.currentPage - 1) * page.pageSize,
          maxResultCount: page.pageSize,
          ...formValues,
        });
        return {
          total: res.totalCount,
          items: res.items,
        };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    zoom: true,
    refresh: true,
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'inventory-management',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [InventoryModal, modalApi] = useVbenModal({
  connectedComponent: inventoryModal,
});

const fileList = ref([]);
const uploading = ref(false);

async function handleAdd() {
  modalApi.setData({});
  modalApi.open();
}

async function handleEdit(record: InventoryDto) {
  modalApi.setData({ id: record.id });
  modalApi.open();
}

function handleDelete(id: any) {
  deleteInventory(id).then(() => {
    notification['success']({
      duration: 2,
      message: $t('pages.common.deleteSuccess'),
    });
    tableApi.query();
  });
}

async function handleExportTemplate() {
  try {
    const blob = await exportInventoryTemplate();
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '库存导入模板.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error: any) {
    notification['error']({
      message: '导出模板失败',
      description: error.message || '未知错误',
    });
  }
}

async function handleExportSelected() {
  const selectedRows = tableApi.grid.getCheckboxRecords();

  const ids = selectedRows.map((row) => row.id);
  try {
    // 根据最新的后端定义，发送包含 Ids 属性的对象
    const blob = await exportInventories(ids);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '库存导出.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error: any) {
    notification['error']({
      message: '导出失败',
      description: error.message || '未知错误',
    });
  }
}

const handleImport = async (options: any) => {
  const { file } = options;
  uploading.value = true;
  try {
    const result: InventoryManagementImportResult = await importInventories(file);
    if (result.success) {
      notification['success']({
        message: '导入成功',
        description: `总行数: ${result.totalRows}, 成功: ${result.successCount}, 失败: ${result.errorCount}`,
      });
      tableApi.query();
    } else {
      let errorMsg = `导入失败: ${result.message}\n`;
      if (result.errors && result.errors.length > 0) {
        errorMsg += '错误详情:\n';
        result.errors.forEach(err => {
          errorMsg += `行 ${err.rowIndex}: ${err.errorMessage}\n`;
        });
      }
      notification['error']({
        message: '导入失败',
        description: errorMsg,
        duration: 0, // Keep notification open until manually closed
      });
    }
  } catch (error: any) {
    notification['error']({
      message: '导入失败',
      description: error.message || '未知错误',
    });
  } finally {
    uploading.value = false;
    fileList.value = [];
  }
};

</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="库存管理列表">
      <template #toolbar-tools>
        <Button v-if="hasAccessByCodes(['Wms.InventoryManagements.Create'])"  class="mr-2" type="primary" @click="handleAdd">
          新增库存
        </Button>
        <Upload class="mr-2" v-model:file-list="fileList" :customRequest="handleImport" :showUploadList="false"
          :disabled="uploading" accept=".xlsx,.xls">
          <Button v-if="hasAccessByCodes(['Wms.InventoryManagements.Import'])"  type="primary" :loading="uploading">
            导入库存
          </Button>
        </Upload>
        <Button  v-if="hasAccessByCodes(['Wms.InventoryManagements.Import'])"  class="mr-2" @click="handleExportTemplate">
          导入模板
          <SvgDownloadIcon />
        </Button>
        <Button  v-if="hasAccessByCodes(['Wms.InventoryManagements.Export'])"  class="mr-2" @click="handleExportSelected">
          导出选中/所有
          <SvgDownloadIcon />
        </Button>
      </template>
      <template #action="{ row }">
        <Space>
          <Button v-if="hasAccessByCodes(['Wms.InventoryManagements.Update'])" class="ml-2" size="small" type="primary" :ghost="true" @click="handleEdit(row)">{{
            $t('pages.common.edit') }}</Button>
          <Popconfirm title="确定删除?" @confirm="handleDelete(row.id)">
            <Button v-if="hasAccessByCodes(['Wms.InventoryManagements.Delete'])" class="ml-2" size="small" :danger="true" :ghost="true" type="primary">{{ $t('pages.common.delete')
            }}</Button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <InventoryModal @reload="tableApi.query()" />
  </Page>
</template>
